import Flutter
import Foundation
import UIKit
import ZendeskSDK
import ZendeskSDKLogger
import ZendeskSDKMessaging

public class ZendeskPlugin: NSObject, FlutterPlugin, UIApplicationDelegate {
  public static func register(with registrar: FlutterPluginRegistrar) {
    let channel = FlutterMethodChannel(
      name: "zendesk_plugin", binaryMessenger: registrar.messenger())
    let instance = ZendeskPlugin()
    registrar.addMethodCallDelegate(instance, channel: channel)
  }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
    switch call.method {
    case "initZendeskSDK":
      if #available(iOS 13.0.0, *) {
        initZendeskSDK(key: (call.arguments as? String) ?? "", result: result)
      } else {
        print("iOS 13.0.0 以上版本才支持 Zendesk SDK")
      }
    case "pushToConversation":
      pushToConversation()
      result(true)
    case "getUnreadCount":
      result(getUnreadCount())
    case "setLoggerEnabled":
      setLoggerEnabled(enable: call.arguments as? Bool ?? false)
      result(true)
    case "setLoggerLevel":
      setLoggerLevel(level: call.arguments as? Int)
      result(true)
    default:
      result(FlutterMethodNotImplemented)
    }
  }


  // 初始化SDK
  @available(iOS 13.0.0, *)
  private func initZendeskSDK(key: String, result: @escaping FlutterResult) {
    Zendesk.initialize(
      withChannelKey: key,
      messagingFactory: DefaultMessagingFactory()
    ) { rsp in
      if case let .failure(error) = rsp {
        print("Messaging did not initialize.\nError: \(error.localizedDescription)")
        result(false)
      } else {
        print("Zendesk SDK 初始化成功")

        if let groupURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.tewamoto.wwww") {
          print("group.共享路径可用: \(groupURL)")
        } else {
          print("group.共享路径不可用")
        }
        result(true)
      }
    }
  }

  // 进入会话页面
  private func pushToConversation() {
    guard let viewController = Zendesk.instance?.messaging?.messagingViewController() else {
      return
    }
    // 使用方式
    if let currentVC = UIApplication.shared.keyWindow?.rootViewController {
      print("present UINavigationController")
      currentVC.present(UINavigationController(rootViewController: viewController), animated: true)
    } else {
      print("当前控制器不存在")
    }
  }

  // 获取未读消息数
  private func getUnreadCount() -> Int {
    return Zendesk.instance?.messaging?.getUnreadMessageCount() ?? 0
  }

  // 是否显示日志
  private func setLoggerEnabled(enable: Bool) {
    Logger.enabled = enable
  }

  // 设置日志级别
  private func setLoggerLevel(level: Int?) {
    Logger.level = ZendeskSDKLogger.LogLevel(rawValue: level ?? 2) ?? .default
  }
}
